#include"Moldel.hpp"
#include"Task.hpp"
#include<time.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
void Save(string message)
{
    string target =  "./log.txt";
    FILE* fp = fopen(target.c_str(),"a");
    if(!fp)
    {
        cerr<<"fopen"<<endl;
        return;
    }
    fputs(message.c_str(),fp);
    fputs("\n",fp);
    cout<<"保存完成"<<endl;
    fclose(fp);
}
void* productor(void* argv)
{
    Block_Queue<CalTask>* _bq = static_cast<BlockQueue<SaveTask,CalTask>*>(argv)->_cq;
    while(1)
    {
        int tem1 = rand()%10;
        int tem2 = rand()%6;
        int opCode = rand()%s.size();
        CalTask t(tem1,tem2,s[opCode],MyMath);
        _bq->push(t);
        cout<<"生产数据："<<t.toTaskString()<<endl;
        sleep(1);
    }
}
void* consumer(void* argv)
{
    Block_Queue<CalTask>* cq = static_cast<BlockQueue<SaveTask,CalTask>*>(argv)->_cq;
    Block_Queue<SaveTask>* sq = static_cast<BlockQueue<SaveTask,CalTask>*>(argv)->_sq;
    sleep(4);
    while(1)
    {
        CalTask t;
        cq->pop(&t);
        string result = t();
        cout<<"消费数据："<<result<<endl;
        SaveTask save(result,Save);
        sq->push(save);
        cout<<"推送保存完成："<<t()<<endl;
        usleep(123654);
    }
}
void * saver(void* argv)
{
    Block_Queue<SaveTask>* sq = static_cast<BlockQueue<SaveTask,CalTask>*>(argv)->_sq;
    while(1)
    {
        SaveTask t;
        sq->pop(&t);
        t();
    }
}
int main()
{
    //#define NUM 5
    srand((unsigned long)time(nullptr)^getpid());
    BlockQueue<SaveTask,CalTask> bq;
    bq._cq = new Block_Queue<CalTask>();
    bq._sq = new Block_Queue<SaveTask>();
    pthread_t t1,t2,t3;
    pthread_create(&t1,nullptr,productor,&bq);
    pthread_create(&t2,nullptr,consumer,&bq);
    pthread_create(&t3,nullptr,saver,&bq);
    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
}